package com.ruoyi.web.controller.gcgl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DecimalCalculateUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.GcKqworks;
import com.ruoyi.gcgl.domain.GcProject;
import com.ruoyi.gcgl.domain.GcYgtj;
import com.ruoyi.gcgl.service.IGcKqworksService;
import com.ruoyi.gcgl.service.IGcProjectService;
import com.ruoyi.gcgl.service.IGcYgtjService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用工统计Controller
 * 
 * @author ruoyi
 * @date 2023-05-01
 */
@Controller
@RequestMapping("/gcgl/ygtj")
public class GcYgtjController extends BaseController{
    private String prefix = "gcgl/ygtj";

    @Autowired
    private IGcYgtjService gcYgtjService;
    @Autowired
    private IGcKqworksService gcKqworksService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IGcProjectService gcProjectService;

    @RequiresPermissions("gcgl:ygtj:view")
    @GetMapping()
    public String ygtj(ModelMap mmap){
    	GcProject gcProject = new GcProject();
    	gcProject.setDeleteFlag(1);
    	List<GcProject> projectlis = gcProjectService.selectGcProjectList(gcProject);
    	mmap.put("projectlis", projectlis);
    	for(GcProject obj:projectlis){
    		obj.setName("("+obj.getOrderNo()+")"+obj.getName());
    	}
        return prefix + "/ygtj";
    }

    /**
     * 查询用工统计列表
     */
    @RequiresPermissions("gcgl:ygtj:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GcYgtj gcYgtj){
        startPage();
        gcYgtj.setDeleteFlag(1);
        if(gcYgtj.getMonth()!=null && !gcYgtj.getMonth().equals("")){
        	gcYgtj.setYear(gcYgtj.getMonth().split("-")[0]);
            gcYgtj.setMonth(gcYgtj.getMonth().split("-")[1].replace("0", ""));
        }
        List<GcYgtj> list = gcYgtjService.selectGcYgtjList(gcYgtj);
        return getDataTable(list);
    }

    /**
     * 导出用工统计列表
     */
    @RequiresPermissions("gcgl:ygtj:export")
    @Log(title = "用工统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GcYgtj gcYgtj){
        List<GcYgtj> list = gcYgtjService.selectGcYgtjList(gcYgtj);
        ExcelUtil<GcYgtj> util = new ExcelUtil<GcYgtj>(GcYgtj.class);
        return util.exportExcel(list, "用工统计数据");
    }

    /**
     * 新增用工统计
     */
    @GetMapping("/add")
    public String add(){
        return prefix + "/add";
    }

    /**
     * 新增保存用工统计
     */
    @RequiresPermissions("gcgl:ygtj:add")
    @Log(title = "用工统计", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public synchronized AjaxResult addSave(){
    	try {
    		GcKqworks gcKqworks = new GcKqworks();
        	gcKqworks.setDeleteFlag(1);
        	gcKqworks.setStatus(0);
        	List<GcKqworks> kqlis = gcKqworksService.selectGcKqworksList(gcKqworks);
        	
        	for(GcKqworks kq:kqlis){
        		String[] peopleIds = kq.getPeopleIds().split(",");
        		String[] peopleNames = kq.getPeopleName().split(",");
        		
        		for(int i=0;i<peopleIds.length;i++){
        			GcYgtj gcYgtj = new GcYgtj();
        			gcYgtj.setYear(String.valueOf(kq.getRq().getYear()+1900));
        			gcYgtj.setMonth(String.valueOf(kq.getRq().getMonth()+1));
        			gcYgtj.setDay(String.valueOf(kq.getRq().getDay()));
        			gcYgtj.setBanz(kq.getBanz());
        			gcYgtj.setDaib(kq.getDaib());
        			gcYgtj.setCode(kq.getCode());
        			gcYgtj.setProjectName(kq.getProjectName());
        			gcYgtj.setJc(kq.getJc());
        			gcYgtj.setDescs(kq.getDescs());
        			
        			SysUser user = userService.selectUserById(Long.parseLong(peopleIds[i]));
        			
        			gcYgtj.setRx(Double.valueOf(Double.parseDouble(user.getRemark().trim())));//日薪
        			gcYgtj.setJzje(
        					Double.valueOf(Double.parseDouble(gcYgtj.getRx().toString())
        							*Double.parseDouble(gcYgtj.getDescs().toString())));
        			gcYgtj.setPeopleIds(peopleIds[i]);
        			gcYgtj.setPeopleName(peopleNames[i]);
        			gcYgtj.setJkrName(peopleNames[i]);
        			gcYgtj.setStatus(0);
        			gcYgtj.setDeleteFlag(1);
        			gcYgtj.setCreateAt(new Date());
        			gcYgtj.setUpdateAt(new Date());
        			gcYgtj.setCreateUser(getLoginName());
        			gcYgtj.setUpdateUser(getLoginName());
            		gcYgtjService.insertGcYgtj(gcYgtj);
        		}
        		
        		//更新考勤记录表
        		GcKqworks kqwork = new GcKqworks();
        		kqwork.setId(kq.getId());
        		kqwork.setStatus(3);
        		gcKqworksService.updateGcKqworks(kqwork);
        	}
		} catch (Exception e) {
			// TODO: handle exception
			return toAjax(0);
		}
    	
        return toAjax(1);
    }

    /**
     * 修改用工统计
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcYgtj gcYgtj = gcYgtjService.selectGcYgtjById(id);
        mmap.put("gcYgtj", gcYgtj);
        return prefix + "/edit";
    }

    /**
     * 修改保存用工统计
     */
    @Log(title = "用工统计", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GcYgtj gcYgtj)
    {
        return toAjax(gcYgtjService.updateGcYgtj(gcYgtj));
    }

    /**
     * 删除用工统计
     */
    @RequiresPermissions("gcgl:ygtj:remove")
    @Log(title = "用工统计", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(gcYgtjService.deleteGcYgtjByIds(ids));
    }
    
    @GetMapping("/ygtjls")
    public String ygtjls(ModelMap mmap){
    	GcProject gcProject = new GcProject();
    	gcProject.setDeleteFlag(1);
    	List<GcProject> projectlis = gcProjectService.selectGcProjectList(gcProject);
    	mmap.put("projectlis", projectlis);
    	for(GcProject obj:projectlis){
    		obj.setName("("+obj.getOrderNo()+")"+obj.getName());
    	}
        return prefix + "/ygtjls";
    }
    
    @GetMapping("/ygtjwq")
    public String ygtjwq(ModelMap mmap){
    	GcProject gcProject = new GcProject();
    	gcProject.setDeleteFlag(1);
    	List<GcProject> projectlis = gcProjectService.selectGcProjectList(gcProject);
    	mmap.put("projectlis", projectlis);
    	for(GcProject obj:projectlis){
    		obj.setName("("+obj.getOrderNo()+")"+obj.getName());
    	}
        return prefix + "/ygtjwq";
    }
    
    @GetMapping("/ygtjMonth")
    public String ygtjMonth(ModelMap mmap){
    	GcProject gcProject = new GcProject();
    	gcProject.setDeleteFlag(1);
    	List<GcProject> projectlis = gcProjectService.selectGcProjectList(gcProject);
    	mmap.put("projectlis", projectlis);
    	for(GcProject obj:projectlis){
    		obj.setName("("+obj.getOrderNo()+")"+obj.getName());
    	}
        return prefix + "/ygtjMonth";
    }
    
    /**
     * 查询用工统计列表Month
     */
    @PostMapping("/listMonth")
    @ResponseBody
    public TableDataInfo listMonth(GcYgtj gcYgtj){
        startPage();
        gcYgtj.setDeleteFlag(1);
        if(gcYgtj.getMonth()!=null && !gcYgtj.getMonth().equals("")){
        	gcYgtj.setYear(gcYgtj.getMonth().split("-")[0]);
            gcYgtj.setMonth(gcYgtj.getMonth().split("-")[1].replace("0", ""));
        }
        List<GcYgtj> list = gcYgtjService.selectGcYgtjList4Month(gcYgtj);
        return getDataTable(list);
    }
    
    @GetMapping("/ygtjPeople")
    public String ygtjPeople(ModelMap mmap){
    	GcProject gcProject = new GcProject();
    	gcProject.setDeleteFlag(1);
    	List<GcProject> projectlis = gcProjectService.selectGcProjectList(gcProject);
    	mmap.put("projectlis", projectlis);
    	for(GcProject obj:projectlis){
    		obj.setName("("+obj.getOrderNo()+")"+obj.getName());
    	}
        return prefix + "/ygtjPeople";
    }
    
    /**
     * 查询用工统计列表Month
     */
    @PostMapping("/listPeople")
    @ResponseBody
    public TableDataInfo listPeople(GcYgtj gcYgtj){
        startPage();
        gcYgtj.setDeleteFlag(1);
        if(gcYgtj.getMonth()!=null && !gcYgtj.getMonth().equals("")){
        	gcYgtj.setYear(gcYgtj.getMonth().split("-")[0]);
            gcYgtj.setMonth(gcYgtj.getMonth().split("-")[1].replace("0", ""));
        }
        List<GcYgtj> list = gcYgtjService.selectGcYgtjList4People(gcYgtj);
        return getDataTable(list);
    }
    
    /**
     * 月班组工时表
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/ygtjMonthPrint/{month}")
    public String ygtjMonthPrint(@PathVariable("month") String month, ModelMap mmap){
    	
    	GcYgtj gcYgtj = new GcYgtj();
    	gcYgtj.setDeleteFlag(1);
    	gcYgtj.setYear(month.substring(0,4));
    	gcYgtj.setMonth(Integer.parseInt(month.substring(5,7))+"");
    	List<GcYgtj> monthlis = gcYgtjService.selectGcYgtjList4Month(gcYgtj);
    	
    	double totalDays = 0.0;
    	double totalhej = 0.0;
    	for(GcYgtj ygtj:monthlis){
    		totalDays = DecimalCalculateUtil.add(totalDays, Double.valueOf(ygtj.getDescs().toString()));
    		totalhej  = DecimalCalculateUtil.add(totalhej, Double.valueOf(ygtj.getJzje().toString()));
    	}
    	
    	mmap.put("years", month.substring(0,4));
    	mmap.put("month", month.substring(5,7));
    	mmap.put("monthlis", monthlis);
    	mmap.put("totalDays", totalDays);
    	mmap.put("totalhej", totalhej);
        return prefix + "/ygtjMonthPrint";
    }
    
    /**
     * 考勤表项目汇总
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/ygtjPeoplePrint/{month}")
    public String ygtjPeoplePrint(@PathVariable("month") String month, ModelMap mmap){
    	//当月天数
    	int daySize = DateUtils.getDaysByDate(month);
    	List<Integer> days = new ArrayList<Integer>();
    	Double hj = 0.0;//总合计
    	for(int i =0;i<daySize;i++){
    		days.add(i+1);
    	}
    	mmap.put("daylis", days);
    	
    	//当月人员列表
    	GcYgtj gcYgtj = new GcYgtj();
    	gcYgtj.setDeleteFlag(1);
    	gcYgtj.setYear(month.substring(0,4));
    	gcYgtj.setMonth(Integer.parseInt(month.substring(5,7))+"");
    	List<GcYgtj> peoplelis = gcYgtjService.selectGcYgtjPeople(gcYgtj);
    	
    	List<GcYgtj> xjlis = gcYgtjService.selectGcYgtjXj(gcYgtj);
    	List<String> dayxjs = new ArrayList<String>();
    	for(int i =0;i<daySize;i++){
			Integer day = i+1;
			if(xjlis!=null && xjlis.size()>0){
				for(GcYgtj obj:xjlis){
	    			if(obj.getDay().equals(day.toString())){
	    				dayxjs.add(obj.getDescs()+"");
	    			}else{
	    				dayxjs.add("0");
	    			}
	    		}
			}else{
				dayxjs.add("0");
			}
		}
    	mmap.put("dayxjs", dayxjs);
    	
    	List<Map> replis = new ArrayList<Map>();
    	for(GcYgtj ygtj:peoplelis){
    		
    		GcYgtj l_gcYgtj = new GcYgtj();
    		l_gcYgtj.setDeleteFlag(1);
    		l_gcYgtj.setYear(month.substring(0,4));
    		l_gcYgtj.setMonth(Integer.parseInt(month.substring(5,7))+"");
    		l_gcYgtj.setPeopleIds(ygtj.getPeopleIds());
    		l_gcYgtj.setJc("正常");
    		List<GcYgtj> peopleJcZc = gcYgtjService.selectGcYgtjList4PeoplePrint(l_gcYgtj);
    		
    		List<String> dayJcZc = new ArrayList<String>();
    		for(int i =0;i<daySize;i++){
    			Integer day = i+1;
    			if(peopleJcZc!=null && peopleJcZc.size()>0){
    				for(GcYgtj zcObj:peopleJcZc){
    	    			if(zcObj.getDay().equals(day.toString())){
    	    				dayJcZc.add(zcObj.getDescs()+"");
    	    			}else{
    	    				dayJcZc.add("0");
    	    			}
    	    		}
    			}else{
    				dayJcZc.add("0");
    			}
    		}
    		
    		GcYgtj c_gcYgtj = new GcYgtj();
    		c_gcYgtj.setDeleteFlag(1);
    		c_gcYgtj.setYear(month.substring(0,4));
    		c_gcYgtj.setMonth(Integer.parseInt(month.substring(5,7))+"");
    		c_gcYgtj.setPeopleIds(ygtj.getPeopleIds());
    		c_gcYgtj.setJc("加班");
    		List<GcYgtj> peopleJcJb = gcYgtjService.selectGcYgtjList4PeoplePrint(c_gcYgtj);
    		
    		List<String> dayJcJb = new ArrayList<String>();
    		for(int i =0;i<daySize;i++){
    			Integer day = i+1;
    			if(peopleJcJb!=null && peopleJcJb.size()>0){
		    		for(GcYgtj jbObj:peopleJcJb){
		    			if(jbObj.getDay().equals(day.toString())){
		    				dayJcJb.add(jbObj.getDescs()+"");
		    			}else{
		    				dayJcJb.add("0");
		    			}
		    		}
    			}else{
    				dayJcJb.add("0");
    			}
    		}
    		//正常
    		Map rep1 = new HashMap();
    		rep1.put("peopleName", ygtj.getPeopleName());
    		rep1.put("peopleCount", peopleJcZc.size()==0?"0":peopleJcZc.get(0).getDescs());
    		rep1.put("peopleTotal", 
    				DecimalCalculateUtil.add(
    						Double.valueOf(peopleJcJb.size()==0?"0":peopleJcJb.get(0).getDescs().toString()), 
    						Double.valueOf(peopleJcZc.size()==0?"0":peopleJcZc.get(0).getDescs().toString())
    						));
    		rep1.put("peopleJclis", dayJcZc);
    		replis.add(rep1);
    		
    		//加班
    		Map rep = new HashMap();
    		rep.put("peopleName", ygtj.getPeopleName());
    		rep.put("peopleCount", peopleJcJb.size()==0?"0":peopleJcJb.get(0).getDescs());
    		rep.put("peopleTotal", 
    				DecimalCalculateUtil.add(
    						Double.valueOf(peopleJcJb.size()==0?"0":peopleJcJb.get(0).getDescs().toString()), 
    						Double.valueOf(peopleJcZc.size()==0?"0":peopleJcZc.get(0).getDescs().toString())
    						));
    		rep.put("peopleJclis", dayJcJb);
    		replis.add(rep);
    		
    		//小计=合计
    		hj += DecimalCalculateUtil.add(
					Double.valueOf(peopleJcJb.size()==0?"0":peopleJcJb.get(0).getDescs().toString()), 
					Double.valueOf(peopleJcZc.size()==0?"0":peopleJcZc.get(0).getDescs().toString())
					);
    	}
    	mmap.put("replis", replis);
    	mmap.put("years", month.substring(0,4));
    	mmap.put("month", month.substring(5,7));
    	mmap.put("hj", hj);
        return prefix + "/ygtjPeoplePrint";
    }
}